import  request, {extend } from 'umi-request';
import { message, } from 'antd';


// 服务端返回值统一错误处理
const errorHandler = function(error: any) {
  const codeMap = {
    '021': 'An error has occurred',
    '022': 'It’s a big mistake,',
    // ....
  };
  if (error.response) {
    console.log(error.response.status); // 例如：code为200, 404
    console.log(error.data); // 返回值
    if (error.response.status > 400){
      message.error('出错了：' + (error.data.message ? error.data.message : error.data));
    }
  } else {
    // The request was made but no response was received or error occurs when setting up the request.
    message.error('网络异常！')
  }

  throw error; // If throw. The error will continue to be thrown.

  // return {some: 'data'}; If return, return the value as a return. If you don't write it is equivalent to return undefined, you can judge whether the response has a value when processing the result.
  // return {some: 'data'};
};

const extendRequest = extend({ errorHandler });



export const getUserList = async (params: any) => {
  const data = extendRequest('/api/users', {
    method: 'get',
  }).then(function(response) {
    // console.log('service服务层--成功', response);
    return response
  }).catch(function(error) {
      console.log('service服务层--失败', error);
      return false
    });

  return data
};




export const toEditUpdateInfo = async ( {id, values}: {id: number, values: object} ) => {
  return request(`/api/users/${id}`, {
    method: 'put',
    data: values,
  }).then(function(response) {
    console.log('service服务层--修改成功', response);
    message.success('修改成功');
    return true
  }).catch(function(error) {
    console.log('service服务层--失败', error);
    message.error('失败了，服务器异常！')
    return false
  })
};


export const toDeleteInfo = async ( {id}: {id: number} ) => {
  return request(`/api/users/${id}`, {
    method: 'delete',
  }).then(function(response) {
    console.log('删除--service服务层--成功', response);
    message.success('删除成功');
    return true
  }).catch(function(error) {
    console.log('删除--service服务层--失败', error);
    message.error('失败了，服务器异常！')
    return false
  })
};







export const toAddUserInfo = async ( {values}: {values: object} ) => {
  console.log('添加传参---service层', values);
  return request('/api/users', {
    method: 'post',
    data: values,
  }).then(function(response) {
    console.log('添加--service服务层--成功', response);
    message.success('添加成功');
    return true

  }).catch(function(error) {
    console.log('添加--service服务层--失败', error);
    message.error('失败了，服务器异常！')
    return false
  })
};
